<template>
  <div class="teacher-container">
    <el-container>
      <el-header>
        <div class="header-content">
          <h2>教师工作台</h2>
          <div class="header-actions">
            <span>欢迎，{{ authStore.user?.name }}</span>
            <el-button type="danger" size="small" @click="handleLogout">
              退出登录
            </el-button>
          </div>
        </div>
      </el-header>
      
      <el-main>
        <!-- 所有课程展示 -->
        <el-card style="margin-bottom: 20px;">
          <template #header>
            <div class="card-header">
              <span>所有课程</span>
              <el-tag type="info">共 {{ allCourses.length }} 门课程</el-tag>
            </div>
          </template>
          
          <el-table :data="allCourses" style="width: 100%">
            <el-table-column prop="title" label="课程名称" width="180" />
            <el-table-column prop="description" label="课程描述" />
            <el-table-column prop="teacher" label="授课教师" width="120" />
            <el-table-column prop="capacity" label="容量" width="80" />
            <el-table-column prop="enrolled" label="已选" width="80" />
            <el-table-column prop="schedule" label="上课时间" width="150" />
            <el-table-column prop="location" label="上课地点" width="120" />
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'open' ? 'success' : 'warning'">
                  {{ row.status === 'open' ? '开放选课' : '已满员' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 我的课程管理 -->
        <el-card>
          <template #header>
            <div class="card-header">
              <span>我的课程</span>
              <el-button type="primary" @click="showAddDialog = true">
                发布新课程
              </el-button>
            </div>
          </template>
          
          <el-table :data="teacherCourses" style="width: 100%">
            <el-table-column prop="title" label="课程名称" width="180" />
            <el-table-column prop="description" label="课程描述" />
            <el-table-column prop="capacity" label="容量" width="80" />
            <el-table-column prop="enrolled" label="已选" width="80" />
            <el-table-column prop="schedule" label="上课时间" width="150" />
            <el-table-column prop="location" label="上课地点" width="120" />
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'open' ? 'success' : 'warning'">
                  {{ row.status === 'open' ? '开放选课' : '已满员' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button size="small" @click="editCourse(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteCourse(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-main>
    </el-container>
    
    <!-- 添加/编辑课程对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingCourse ? '编辑课程' : '发布新课程'"
      width="500px"
    >
      <el-form
        ref="courseFormRef"
        :model="courseForm"
        :rules="courseRules"
        label-width="80px"
      >
        <el-form-item label="课程名称" prop="title">
          <el-input v-model="courseForm.title" placeholder="请输入课程名称" />
        </el-form-item>
        
        <el-form-item label="课程描述" prop="description">
          <el-input
            v-model="courseForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入课程描述"
          />
        </el-form-item>
        
        <el-form-item label="容量" prop="capacity">
          <el-input-number
            v-model="courseForm.capacity"
            :min="1"
            :max="200"
            placeholder="请输入课程容量"
          />
        </el-form-item>
        
        <el-form-item label="上课时间" prop="schedule">
          <el-input v-model="courseForm.schedule" placeholder="如：周一 14:00-16:00" />
        </el-form-item>
        
        <el-form-item label="上课地点" prop="location">
          <el-input v-model="courseForm.location" placeholder="请输入上课地点" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitCourse">
          {{ editingCourse ? '更新' : '发布' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { useCoursesStore } from '@/stores/courses'

const router = useRouter()
const authStore = useAuthStore()
const coursesStore = useCoursesStore()

const courseFormRef = ref()
const showAddDialog = ref(false)
const editingCourse = ref(null)
const submitLoading = ref(false)

const courseForm = reactive({
  title: '',
  description: '',
  capacity: 50,
  schedule: '',
  location: ''
})

const courseRules = {
  title: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入课程描述', trigger: 'blur' }],
  capacity: [{ required: true, message: '请输入课程容量', trigger: 'blur' }],
  schedule: [{ required: true, message: '请输入上课时间', trigger: 'blur' }],
  location: [{ required: true, message: '请输入上课地点', trigger: 'blur' }]
}

// 获取当前教师的课程
const teacherCourses = computed(() => {
  return coursesStore.getCoursesByTeacher(authStore.user?.name)
})

// 获取所有课程
const allCourses = computed(() => {
  return coursesStore.courses
})

const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

const editCourse = (course) => {
  editingCourse.value = course
  Object.assign(courseForm, {
    title: course.title,
    description: course.description,
    capacity: course.capacity,
    schedule: course.schedule,
    location: course.location
  })
  showAddDialog.value = true
}

const deleteCourse = async (course) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除课程 "${course.title}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const success = coursesStore.deleteCourse(course.id)
    if (success) {
      ElMessage.success('课程删除成功！')
    } else {
      ElMessage.error('课程删除失败！')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除操作失败！')
    }
  }
}

const submitCourse = async () => {
  if (!courseFormRef.value) return
  
  await courseFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (editingCourse.value) {
          // 编辑课程
          const updated = coursesStore.updateCourse(editingCourse.value.id, courseForm)
          if (updated) {
            ElMessage.success('课程更新成功！')
          }
        } else {
          // 添加新课程
          const newCourse = coursesStore.addCourse({
            ...courseForm,
            teacher: authStore.user.name
          })
          if (newCourse) {
            ElMessage.success('课程发布成功！')
          }
        }
        
        showAddDialog.value = false
        resetForm()
      } catch (error) {
        ElMessage.error('操作失败，请重试！')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const resetForm = () => {
  editingCourse.value = null
  Object.assign(courseForm, {
    title: '',
    description: '',
    capacity: 50,
    schedule: '',
    location: ''
  })
}

onMounted(() => {
  coursesStore.initializeCourses()
})
</script>

<style scoped>
.teacher-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-attachment: fixed;
  padding: 20px;
}

.el-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  margin-bottom: 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  height: 70px;
}

.header-content h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  background: linear-gradient(45deg, #3498db, #8e44ad);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-actions span {
  color: #7f8c8d;
  font-weight: 500;
}

.el-main {
  padding: 0;
}

.el-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.el-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

:deep(.el-card__header) {
  background: linear-gradient(45deg, #f8f9fa, #e9ecef);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  border-radius: 16px 16px 0 0;
  padding: 20px 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background: linear-gradient(45deg, #f8f9fa, #e9ecef);
}

:deep(.el-table th) {
  background: transparent;
  color: #2c3e50;
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
}

:deep(.el-table tr:hover) {
  background-color: rgba(116, 75, 162, 0.05);
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-button--primary) {
  background: linear-gradient(45deg, #3498db, #2980b9);
  border: none;
}

:deep(.el-button--danger) {
  background: linear-gradient(45deg, #e74c3c, #c0392b);
  border: none;
}

:deep(.el-tag) {
  border-radius: 20px;
  font-weight: 500;
}

:deep(.el-dialog) {
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

:deep(.el-dialog__header) {
  background: linear-gradient(45deg, #f8f9fa, #e9ecef);
  border-radius: 16px 16px 0 0;
  padding: 20px 24px;
}

:deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid #ddd;
  transition: all 0.3s ease;
}

:deep(.el-input__inner:focus) {
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

:deep(.el-input-number) {
  border-radius: 8px;
}
</style>